package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.Arrays;
import java.util.List;

@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TimeLineService timeLineService;

    /**
     * 发布动态，返回动态的ID
     *
     * @param movement
     */
    @Override
    public String publish(Movement movement) {
        //1.保存动态详情
        try {
            //设置pid，发布时间
            movement.setPid(idWorker.getNextId("movement"));
            movement.setCreated(System.currentTimeMillis());
            mongoTemplate.save(movement);
            timeLineService.saveTimeLine(movement.getUserId(), movement.getId());

        } catch (Exception e) {
            //忽略事务处理
            e.printStackTrace();
        }
        return movement.getId().toHexString();
    }

    /**
     * 查询动态，可查询本人，好友
     *
     * @param userIds
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult findMove(List<Long> userIds, Integer page, Integer pagesize) {

        Criteria criteria = Criteria.where("userId").in(userIds).and("state").is(1);

        Query query = Query.query(criteria);
        long count = mongoTemplate.count(query, Movement.class);
        query.with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        PageResult pr = new PageResult(page, pagesize, count, movements);
        return pr;
    }

    /**
     * 随机获取多条动态
     *
     * @param
     * @return
     */
    @Override
    public List<Movement> randomMovements(Integer counts) {
        //创建统计对象，设置统计参数
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class, Aggregation.sample(counts));
        //调用MongoTemplate方法统计
        AggregationResults<Movement> results = mongoTemplate.aggregate(aggregation, Movement.class);
        //获取统计结果
        List<Movement> movementList = results.getMappedResults();
        return movementList;
    }

    /**
     * 根据pid获取数组查询动态
     *
     * @param pids
     * @return
     */
    @Override
    public List<Movement> findMovementsByPids(List<Long> pids) {
        Query query = Query.query(Criteria.where("pid").in(pids));
        return mongoTemplate.find(query, Movement.class);
    }

    @Override
    public Movement movementDetails(String id) {
        return mongoTemplate.findById(id, Movement.class);
    }

    /**
     * 根据Id查询
     *
     * @param uid
     * @param state
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult findByUserId(Long uid, Integer state, Integer page, Integer pagesize) {
        Query query = new Query();
        if (uid != null) {
            query.addCriteria(Criteria.where("userId").is(uid));
        }
        if (state != null) {
            query.addCriteria(Criteria.where("state").is(state));
        }
        long count = mongoTemplate.count(query, Movement.class);
        query.skip((page-1)*pagesize).limit(pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,count,movementList);
    }

    /**
     * 更新动态的状态
     * @param movementId
     * @param state
     */
    @Override
    public void updateState(String movementId, int state) {
        Update update = Update.update("state", state);
        Query query = Query.query(Criteria.where("_id").is(new ObjectId(movementId)));
        mongoTemplate.updateFirst(query,update,Movement.class);
    }

}
